<template>
  <div>
    <el-card v-loading="loading">
      <el-row class="customRow" :gutter="20">
        <el-col :span="24">
          <p class="mr-2">{{ $t("商务卡总资产") }}:</p>
          <p class="mr-2">{{ state.amount || 0 }}</p>
          <div
            class="currency"
            @click="isShow = !isShow"
            v-if="state.cardsCurrencyList.length > 0"
          >
            <span class="cursor-pointer currencyName">
              {{ state.currency }}<el-icon><CaretBottom /></el-icon>
            </span>
            <ul v-if="isShow" class="currencyList">
              <li
                class="flex items-center justify-between cursor-pointer"
                v-for="(item, index) of state.cardsCurrencyList"
                :key="index"
                @click="changeCurrency(item)"
              >
                <span> {{ item.currency }}</span>
                <el-icon
                  class="ml-2"
                  style="color: #f56c6c"
                  v-if="item.currency === state.currency"
                  ><Select
                /></el-icon>
              </li>
            </ul>
          </div>
        </el-col>
      </el-row>
      <div
        class="flex flex-wrap items-center justify-start mb-4 summary-text gap-x-20 gap-y-1"
      >
        <div>
          <span class="text-lg font-medium">{{ $t("总卡片数量") }}:</span>
          <span class="ml-2 text-lg">
            {{ state.cardInfo.total || 0 }}
          </span>
        </div>
        <div>
          <span class="mr-2">{{ $t("活跃") }}:</span>
          <span>{{ state.cardInfo.active || 0 }}</span>
        </div>
        <div>
          <span class="mr-2">{{ $t("冻结") }}:</span>
          <span>{{ state.cardInfo.inactive || 0 }}</span>
        </div>
        <div>
          <span class="mr-2">{{ $t("注销") }}:</span>
          <span>{{ state.cardInfo.closed || 0 }}</span>
        </div>
        <div>
          <span class="mr-2">{{ $t("未激活") }}:</span>
          <span>{{ state.cardInfo.pending || 0 }}</span>
        </div>
        <div>
          <span class="mr-2">{{ $t("创建失败") }}:</span>
          <span>{{ state.cardInfo.failed || 0 }}</span>
        </div>
      </div>

      <div class="flex justify-between operate">
        <div>
          <el-form :inline="true" style="flex: 1" :model="filterForm">
            <el-form-item>
              <el-input
                :placeholder="$t('搜索持卡人姓名或卡号')"
                clearable
                v-model="filterForm.kw"
                @change="filterList"
              >
                <template #append>
                  <el-button icon="Search" @click="filterList" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-date-picker
                style="width: 100%"
                v-model="filterForm.timeData"
                type="datetimerange"
                :range-separator="$t('至')"
                :start-placeholder="$t('开始日期')"
                :end-placeholder="$t('截止日期')"
                @change="filterList"
                :default-time="pickerDefaultTime"
              />
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="filterForm.card_status"
                clearable
                :placeholder="$t('状态')"
                @change="filterList"
              >
                <el-option
                  v-for="item in cardStatus"
                  :key="item.key"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-button type="danger" icon="Plus" size="large" @click="addCard">{{
            $t("创建新卡")
          }}</el-button>
        </div>
      </div>
      <el-divider />
      <div>
        <el-table :data="state.tableData">
          <template #empty>
            <p class="text-lg">{{ $t("还未创建卡片") }}</p>
          </template>
          <el-table-column
            prop="brand"
            :label="$t('卡片预览图')"
            align="center"
          >
            <template #default="scope">
              <img
                src="@/assets/images/列表默认卡面.png"
                alt=""
                class="imgStyle"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="card_number"
            :label="$t('卡片尾号')"
            align="center"
          >
            <template #default="scope">
              {{ scope.row.card_number || "--" }}
            </template>
          </el-table-column>
          <el-table-column
            prop="card_status"
            :label="$t('卡片状态')"
            align="center"
          >
            <template #default="scope">
              <el-tag :type="getCardStatusName(scope.row.card_status)?.type">
                {{ getCardStatusName(scope.row.card_status)?.name }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="name_on_card"
            :label="$t('卡-持卡人姓名')"
            align="center"
          />
          <el-table-column
            prop="category_name"
            :label="$t('卡片类型')"
            align="center"
          >
          </el-table-column>
          <el-table-column
            align="center"
            fixed="right"
            :label="$t('操作')"
            width="180"
          >
            <template #default="scope">
              <el-button
                round
                icon="MoreFilled"
                class="cursor-pointer"
                size="small"
                @click="handleDetails(scope.row)"
                >{{ $t("查看") }}</el-button
              >
              <el-button
                round
                class="cursor-pointer"
                :disabled="scope.row.offline"
                size="small"
                @click="handleParticulars(scope.row)"
                >{{ $t("交易明细") }}</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="flex flex-wrap justify-center mt-5">
        <el-pagination
          class="w-[100%] flex-wrap justify-center gap-y-2"
          background
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageable.total"
          :current-page.sync="pageable.pageNum"
          :page-size="pageable.pageSize"
          :page-sizes="[10, 25, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :small="isSmall"
        />
      </div>
    </el-card>
    <Detail
      :isShowDetail="isShowDetail"
      :cardId="card_id"
      :assetType="asset_type"
      @close="
        () => {
          isShowDetail = false;
        }
      "
    />
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { GetCardsSummary, GetCardsList } from "@/api/card";
import Detail from "./components/detailDrawer.vue";
import { timestamp, pickerDefaultTime, formatDates } from "@/utils/utils";

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const isShow = ref(false);

const state = reactive({
  cardInfo: {},
  tableData: [
    {
      card_number: "",
      card_status: "",
      nick_name: "",
      category_name: "",
      offline: false,
    },
  ],

  cardsCurrencyList: [],
  category_id: "",
  currency: "",
  amount: 0,
});

const pageable = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const cardStatus = computed(() => {
  return [
    { key: 1, name: `${t("未激活")}`, value: "PENDING", type: "warning" },
    { key: 2, name: `${t("活跃")}`, value: "ACTIVE", type: "success" },
    { key: 3, name: `${t("已冻结")}`, value: "INACTIVE", type: "danger" },
    // { key: 4, name: "已挂失", value: "LOST", type: "danger" },
    // { key: 5, name: "已被盗", value: "STOLEN", type: "danger" },
    { key: 6, name: `${t("已注销")}`, value: "CLOSED", type: "info" },
    { key: 7, name: `${t("创建失败")}`, value: "FAILED", type: "danger" },
  ];
});

// 选择币种切换金额
const checkCurrency = () => {
  if (state.cardInfo.accounts && state.cardInfo.accounts.length > 0) {
    const result = state.cardInfo.accounts.filter((item) => {
      return item.currency === state.currency;
    });
    state.amount = result[0].amount;
  }
};

// 币种切换
const changeCurrency = (val) => {
  state.currency = val.currency;
  checkCurrency();
};

// 卡片状态
const getCardStatusName = (status) => {
  return cardStatus.value.find((i) => status === i.value);
};

// 卡片列表
const getCardList = async (listQuery) => {
  try {
    loading.value = true;
    const pageNum = JSON.parse(localStorage.getItem("pageNum"));
    if (pageNum) {
      pageable.value.pageNum = pageNum;
    }
    let query = {
      ...{ page: pageable.value.pageNum, pagesize: pageable.value.pageSize },
      ...listQuery,
    };
    const { page, list } = await GetCardsList(query);
    state.tableData = list || [];
    pageable.value.total = page.total_count || 0;
    loading.value = false;
    localStorage.removeItem("pageNum");
  } catch {
    loading.value = false;
  }
};

const handleCurrentChange = (number) => {
  pageable.value.pageNum = number;
  localStorage.removeItem("pageNum");
  getCardList(filterForm);
};
// 条数
const handleSizeChange = (number) => {
  pageable.value.pageSize = number;
  localStorage.removeItem("pageNum");
  getCardList(filterForm);
};

const addCard = () => {
  router.replace({
    path: `${route.path}/addCard`,
  });
};

const isShowDetail = ref(false);
const card_id = ref("");
const asset_type = ref("");

const handleDetails = (row) => {
  localStorage.setItem("pageNum", pageable.value.pageNum);
  card_id.value = row.card_id;
  asset_type.value = row.asset_type;
  isShowDetail.value = true;
};

const handleParticulars = (row) => {
  router.push({
    path: `/card/transactionRecords`,
    query: { card_id: row.card_id },
  });
};

//筛选组件
const filterForm = reactive({
  kw: "",
  card_status: "",
  purpose: "",
});

const filterList = async () => {
  const newQuery = Object.entries({ ...filterForm }).reduce(
    (acc, [key, value]) => {
      if (value) {
        acc[key] = value;
      }
      return acc;
    },
    {}
  );
  if (newQuery.timeData) {
    newQuery.start = newQuery.timeData[0]
      ? timestamp(newQuery.timeData[0].valueOf())
      : "";
    newQuery.end = newQuery.timeData[1]
      ? timestamp(newQuery.timeData[1].valueOf())
      : "";
    delete newQuery.timeData;
  } else {
    delete newQuery.start;
    delete newQuery.end;
  }
  console.log(newQuery, "newQuery");
  pageable.value.pageNum = pageable.value.pageNum;
  localStorage.setItem("cardFilter", JSON.stringify(newQuery));
  await getCardList(newQuery);
};

const isSmall = ref(false);

const updateSmall = () => {
  isSmall.value = window.innerWidth < 768; // 根据屏幕宽度判断
};

onMounted(async () => {
  const cardId = localStorage.getItem("cardId");
  if (cardId) {
    isShowDetail.value = true;
    card_id.value = cardId;
    localStorage.removeItem("cardId");
  }
  const query = JSON.parse(localStorage.getItem("cardFilter"));
  if (query) {
    await getCardList(query);
    for (let key in query) {
      filterForm[key] = query[key];
    }
    if (query.start && query.end) {
      filterForm.timeData = [formatDates(query.start), formatDates(query.end)];
    }
  } else {
    await getCardList();
  }
  try {
    const data = await GetCardsSummary();
    state.cardInfo = data || {};
    state.cardsCurrencyList = state.cardInfo.accounts || [];
    state.currency = state.cardsCurrencyList[0].currency;
  } catch {}
  checkCurrency();
  updateSmall(); // 初始化时设置
  window.addEventListener("resize", updateSmall); // 监听窗口大小变化
});
onUnmounted(() => {
  window.removeEventListener("resize", updateSmall); // 清理事件监听
});
</script>
<style lang="scss" scoped>
.el-row {
  margin-bottom: 1%;
}
.customRow .el-col {
  p {
    display: inline-block;
    font-size: 18px;
    font-weight: 500;
  }
  span {
    margin-right: 2%;
    line-height: 30px;
  }
}
.summary-text {
  span {
    line-height: 30px;
  }
}
.operate {
  display: flex;
  justify-content: space-between;
  // .el-input {
  //   width: 260px;
  // }
}
.container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.currency {
  display: inline-block;
  position: relative;
  .currencyName {
    display: inline-block;
    width: 60px;
    text-align: center;
    background: rgba(242, 242, 242, 1);
    border-radius: 5px;
  }
  .currencyList {
    background: #fff;
    box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    padding: 5px;
    position: absolute;
    left: 0;
    top: 30px;
    z-index: 999;
  }
}
.imgStyle {
  height: 50px;
  width: 80px;
  margin: 0 auto;
  border-radius: 10px;
  background: rgb(244 244 244);
}
</style>
